package com.wangxiang.sys.manage.service.Impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.druid.sql.PagerUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wangxiang.common.utils.*;
import com.wangxiang.sys.manage.dao.RoleDao;
import com.wangxiang.sys.manage.dao.RoleUserDao;
import com.wangxiang.sys.manage.dao.UserDao;
import com.wangxiang.sys.manage.entity.RoleEntity;
import com.wangxiang.sys.manage.entity.UserEntity;
import com.wangxiang.sys.manage.utils.RedisUtils;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wangxiang.sys.manage.dao.LoginLogGatewayDao;
import com.wangxiang.sys.manage.entity.LoginLogGatewayEntity;
import com.wangxiang.sys.manage.service.LoginLogGatewayService;


@Service("loginLogGatewayService")
public class LoginLogGatewayServiceImpl extends ServiceImpl<LoginLogGatewayDao, LoginLogGatewayEntity> implements LoginLogGatewayService {
    @Autowired
    private LoginLogGatewayDao log;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleUserDao roleUserDao;
    @Autowired
    private RoleDao roleDao;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<LoginLogGatewayEntity> page = this.page(
                new Query<LoginLogGatewayEntity>().getPage(params),
                new QueryWrapper<LoginLogGatewayEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public int addLogs(int userId,int type) {
        LoginLogGatewayEntity loginLogGatewayEntity = new LoginLogGatewayEntity();
        loginLogGatewayEntity.setUserId(userId);
        loginLogGatewayEntity.setTime(new Date());
        if (type==0){
            loginLogGatewayEntity.setType("登录");
        }
        if (type==1){
            loginLogGatewayEntity.setType("退出登录");
        }
        Map<Object, Object> map = redisUtils.hmget("loginOrloginOut");
        Object origin = map.get("Origin");
        if (origin!=null){
            String replace = origin.toString().replace("[","");
            String replace1 = replace.replace("]","");
            loginLogGatewayEntity.setRequestIp(replace1);
        }
        Object agent = map.get("User-Agent");
        if (agent!=null){
            String replace = agent.toString().replace("[","");
            String replace1 = replace.replace("]","");
            loginLogGatewayEntity.setBrowser(replace1);
        }

        int insert = log.insert(loginLogGatewayEntity);


        return insert;
    }

    @Override
    public PageEntity page(HashMap<String, Integer> map) {
        PageHelper.startPage(map.get("pageNum"),map.get("pageSize"));

        List<LoginLogGatewayEntity> loginLogGatewayEntities = log.selectList(null);

        PageInfo<LoginLogGatewayEntity> loginLogGatewayEntityPageInfo = new PageInfo<>(loginLogGatewayEntities);

        PageGenerate pageGenerate = new PageGenerate();
        PageEntity generate = pageGenerate.generate(loginLogGatewayEntityPageInfo);
        return generate;
    }

    @Override
    public List<HashMap<String, Object>> pageMap(List<LoginLogGatewayEntity> list) {

        ArrayList<HashMap<String, Object>> hashMaps = new ArrayList<>();
        for (LoginLogGatewayEntity entity : list) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("doType",entity.getType());

            //查管理员信息

            UserEntity userEntity = userDao.selectById(entity.getUserId());

            BeanMap beanMap = BeanMap.create(userEntity);
            beanMap.forEach((k,v)->{
                map.put(k.toString(),v);
            });

            int roleIdByUser = roleUserDao.getRoleIdByUser(entity.getUserId());
            map.put("roleId",roleIdByUser);
            RoleEntity roleEntity = roleDao.selectById(roleIdByUser);
            map.put("roleName",roleEntity.getName());
            TimeUtils timeUtils = new TimeUtils();
            String time = timeUtils.timeChange(entity.getTime());
            map.put("time",time);


            //解析操作浏览器
            if (entity.getBrowser()!=null){
                UserAgent userAgent = UserAgent.parseUserAgentString(entity.getBrowser());
                if (userAgent!=null){
                    //获取浏览器对象
                    Browser browser = userAgent.getBrowser();
                    //获取操作系统对象
                    OperatingSystem operatingSystem = userAgent.getOperatingSystem();
                    map.put("browserName",browser.getName());
                    map.put("browserType",browser.getBrowserType());
                    map.put("systemName",operatingSystem.getName());

                }
            }
            String nullStr = "";



            //解析ip
            if (entity.getRequestIp()!=null){
                String replace = entity.getRequestIp().replace("http://", "");
                String ip = StringUtils.substringBefore(replace, ":");
                String localhost = "localhost";
                if (localhost.equals(ip)|ip==null){
                    map.put("loginLocation","测试环境");
                }else {
                    String url = "https://apis.map.qq.com/ws/location/v1/ip?ip="+ip+"&key=WMIBZ-JD6KD-GVP46-HCPPN-32NDS-OWFSA";
                    String s = HttpUtil.get(url);
                    if (s!=null){
                        JSONObject jsonObject = JSONObject.parseObject(s);
                        JSONObject result = jsonObject.getJSONObject("result");
                        if (result!=null|!nullStr.equals(result)){
                            JSONObject ad_info = result.getJSONObject("ad_info");
                            if (ad_info!=null|!nullStr.equals(ad_info)){
                                map.put("nation",ad_info.get("nation"));
                                map.put("province",ad_info.get("province"));
                                map.put("city",ad_info.get("city"));
                                map.put("district",ad_info.get("district"));

                                JSONObject location = result.getJSONObject("location");

                                String urlJson = "https://restapi.amap.com/v3/geocode/regeo?key=3ba3e113632f01a6e1ca4f504a0a97ca&location="+location.get("lng")+","+location.get("lat")+"&batch=true&extensions =all";

                                String s1 = HttpUtil.get(urlJson);

                                JSONObject json = JSONObject.parseObject(s1);

                                JSONArray regeocodes = json.getJSONArray("regeocodes");
                                if (regeocodes!=null|!nullStr.equals(regeocodes)){
                                    JSONObject jsonObject1 = regeocodes.getJSONObject(0);
                                    Object formatted_address = jsonObject1.get("formatted_address");
                                    map.put("formatted_address",formatted_address);

                                }

                            }
                        }

                    }

                }
                map.put("ip",ip);

            }








            hashMaps.add(map);




        }

        return hashMaps;
    }

}